package cn.funeralobjects.youtube.dl.extension.controller;

import cn.funeralobjects.youtube.dl.extension.converter.TaskStatusConverter;
import cn.funeralobjects.youtube.dl.extension.service.DownloadService;
import cn.funeralobjects.youtube.dl.extension.utils.SpringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.UUID;

/**
 * @author FuneralObjects
 * Create date: 2020/4/5 5:58 AM
 */
@Component
@ServerEndpoint("/task-status")
public class TaskStatusController {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private DownloadService downloadService;
    private TaskStatusConverter taskStatusConverter;
    private Session session;
    private String key;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        this.downloadService = SpringUtils.getBean(DownloadService.class);
        this.taskStatusConverter = SpringUtils.getBean(TaskStatusConverter.class);
        this.key = key(session);
        downloadService.addNextConsumer(this.key, task -> {
            if(this.session.isOpen()){
                try {
                    this.session.getBasicRemote().sendText(MAPPER.writeValueAsString(taskStatusConverter.toVo(task)));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @OnClose
    public void onClose(){
        downloadService.removeConsumer(this.key);
    }

    private static String key(Session session){
        return session.getId()+":"+ UUID.randomUUID().toString();
    }

}
